<template>
  <div class="custom-field">
    <ElRow class="custom-field-item" v-for="(item , index) in value" :key="index">
      <ElCol :span="5">
        <ElInput :model-value="item.l" placeholder="请输入名称" @update:model-value="onChangeLabel(index, $event)" />
      </ElCol>
      <ElCol :span="15" :offset="1">
        <ElInput :model-value="item.v" placeholder="请输入值" @update:model-value="onChangeValue(index, $event)" />
      </ElCol>
      <ElCol :span="2" :offset="1">
        <ElButton v-if="index" type="primary" link @click="onRemove(index)">删除</ElButton>
        <ElButton v-else type="primary" link @click="onAdd">添加</ElButton>
      </ElCol>
    </ElRow>
  </div>
</template>

<script setup lang="ts">
import { ElButton } from 'element-plus';
import { computed } from 'vue'
interface Props {
  modelValue: string;
  data: object;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  data: () =>({}),
})
const emit = defineEmits()

const value = computed(() => {
  const val = props.modelValue
  if (!val) return [{ l: '', v: '' }]
  const list = JSON.parse(val)
  if (!list.length) return [{ l: '', v: '' }]
  return list
})

const onAdd = () => {
  const val = [...value.value]
  val.push({ l: '', v: '' })
  emit('update:modelValue', JSON.stringify(val))
}

const onRemove = (index) => {
  const val = [...value.value]
  val.splice(index, 1)
  emit('update:modelValue', JSON.stringify(val))
}

const onChangeLabel = (index, l) => {
  const val = [...value.value]
  const obj = Object.assign({}, val[index] || {}, {l})
  val.splice(index, 1, obj)
  emit('update:modelValue', JSON.stringify(val))
}
const onChangeValue =(index, v) => {
  const val = [...value.value]
  const obj = Object.assign({}, val[index] || {}, {v})
  val.splice(index, 1, obj)
  emit('update:modelValue', JSON.stringify(val))
}
</script>

<style lang="scss" scoped>
.custom-field {
  width: 100%;
  &-item + &-item {
    margin-top: 10px;
  }
}
</style>
